package com.chen.music.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.chen.music.model.Rank;
import com.chen.music.service.RankService;
import com.chen.music.util.CommonResult;
import com.chen.music.util.MessageConst;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;


/**
 * <p>
 * 评价 前端控制器
 * </p>
 *
 * @author boat
 * @since 2022-01-13
 */
@RestController
@RequestMapping("/rank")
@Api(tags = "评分管理")
public class RankController {

    @Autowired
    private RankService rankService;

    @GetMapping("/{id}")
    @ApiOperation("根据歌单id获取歌单评分")
    public CommonResult findById(@PathVariable("id") Integer id) {
        try {
            LambdaQueryWrapper<Rank> wrapper = Wrappers.lambdaQuery();
            wrapper.select(Rank::getScore);
            wrapper.eq(id != null, Rank::getSongListId, id);
            List<Rank> ranks = rankService.list(wrapper);
            int result = 0;
            if (ranks != null && ranks.size() > 0) {
                for (Rank rank : ranks) {
                    result += rank.getScore();
                }
            }
            return new CommonResult(200, true, result / ranks.size());
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult(500, false, MessageConst.INTERFACE_EXCEPTION);
        }
    }

    @PostMapping("/add")
    @ApiOperation("新增歌单评分")
    public CommonResult findById(Rank rank) {
        try {
            LambdaQueryWrapper<Rank> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(rank.getSongListId() != null, Rank::getSongListId, rank.getSongListId());
            wrapper.eq(rank.getConsumerId() != null, Rank::getConsumerId, rank.getConsumerId());
            Rank realRank = rankService.getOne(wrapper);
            if (realRank != null) {
                //说明用户在评论以评论过的歌单，则进行评分的更新
                rank.setId(realRank.getId());
                if (rankService.updateById(rank)) {
                    return new CommonResult(200, true, MessageConst.ADD_SCORE_SUCCESS);
                }
                return new CommonResult(200, false, MessageConst.ADD_SCORE_FAIL);
            }
            if (rankService.save(rank)) {
                return new CommonResult(200, true, MessageConst.ADD_SCORE_SUCCESS);
            }
            return new CommonResult(200, false, MessageConst.ADD_SCORE_FAIL);
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult(500, false, MessageConst.INTERFACE_EXCEPTION);
        }
    }
}

